<template>
	<view class="connect">
		<u-navbar v-if="showTop" :border-bottom="false" :custom-back="backHome" back-text="首页" title=""></u-navbar>
		<!-- <view class="helloBox" style="">
			<img src="./hello.png" alt="" />
		</view> -->
		<view class="" style="display: flex; align-items: ;	padding-bottom: 80rpx;width: 100%;">
			<view @click="isPhone=true" style="" :class="isPhone?'login_text_yes':'login_text_no'">
				账号登录
			</view>
			<view @click="isPhone=false" :class="!isPhone?'login_text_yes':'login_text_no'">
				验证码登录
			</view>
		</view>
		<view class="input_item">
			<view class="input_item_left">
				手机号/邮箱
			</view>
			<u-input v-model="model"  :maxlength="25" placeholder="请输入手机号" />
		</view>
		<view v-if="isPhone" class="input_item ">
			<view class="input_item_left ">
				密码
			</view>
			<u-input v-model="code" type="password" :maxlength="11" placeholder="请输入密码" />
			
		</view>
		<view v-else class="input_item ">
			<view class="input_item_left ">
				验证码
			</view>
			<u-input v-model="sms_captcha" type="number" :maxlength="6" placeholder="请输入验证码" />
			<u-button @click="getCode('login')" size="mini" :hair-line='false' :disabled="disabled" :ripple="true" shape="square" ripple-bg-color="#ccc">{{btn_text}}</u-button>
			
		</view>
		<view @click="navto('/pages/login/zhuCe')" style="width: 150rpx;" class="zhuce marginBottom188">
			账号注册
			<u-icon name="arrow-right" class="right" color="#999999" size="27"></u-icon>
		</view>
		<view class="xieyi" :class="isToast?'tiao':''">
			<view @click="isOk = !isOk" class="no" >
				<view v-if="isOk" class="yes"></view>
			</view>
			<span   class="xieyi_text">
			<span  @click="isOk = !isOk">阅读并同意</span> 
			<span style="color: #743a85;" @click="navToXieyi(1)">《用户服务协议》</span>
			以及
			<span style="color: #743a85;"  @click="navToXieyi(2)">《登录政策》</span>
			</span>
		</view>
		<view @click="login" class="btns_login"  >
			账号登录
		</view>
		<view class="other_login_type">
			<view class="other_login_type_title" style="font-size: 26rpx;">
				——— 其他登录方式 ———
			</view>
			<view @click="getWeChatCode" class="login_btn_wx">
				<view class="wx_logo" >
					<img src="./Wechat.png" alt="" style="width: 48rpx;" />
				</view>
				<view class="wx_connect">微信一键登录</view>
			</view>
		</view>
		
	</view>
	
</template>

<script>
	export default {
		data() {
			return {
				showTop:true,
				isPhone: true,
				sms_captcha: '',
				phonecode: '', //短信验证码
				noewPhone: '', //新手机号
				phoneSHow: false, // 修改手机号弹出
				wx_info: {}, //微信登录返回用户信息
				isToast: false,
				code: '',
				model: '',
				isOk: false,
				disabled: false,
				disabled1: false,
				btn_text: '获取验证码',
				btn_text1: '获取验证码',
				time: null,
				times: 120, //剩余时间
				loginType: 1,
				isWixin: false, //是否安装微信
				isSinaweibo: false, //是否安装微博
				
			}
		},

		created() {
			this.isWXBrowser = this.isWXBrowser();
			console.log(this.isWXBrowser, '微信浏览器')
			if (this.isWXBrowser) {
				this.showTop = false
				let code = this.getUrlCode("code");
				if (code) {
					this.code = code
					this.wxLogin(code , 1); //后台登录
				}
				// else {
				// 	this.getWeChatCode(); //微信授权
				// }
			}else{
				let code = this.getUrlCode("code");
				if (code) {
					this.code = code
					this.wxLogin(code , 2); //后台登录
				}
				this.showTop = true
			}
		},

		onShow(data) {
			// this.isWixin = uni.getStorageSync('isWeixin')
			// this.isSinaweibo = uni.getStorageSync('isSinaweibo')
			// console.log(isWixin, '111')
		},
		methods: {
			wxLogin(code , type) {
				this.$wqzApi.getWechatInfoByAPP({
					code: code,
					type:type
				}).then(res => {
					uni.showToast({
						title: '登录成功',
						icon: 'success'
					})
					uni.setStorageSync('token', res.data)
					setTimeout(() => {
						uni.switchTab({
							url: '/pages/self/self'
						})
					}, 1500)
				})
			},
			//判断是否是微信内置的浏览器
			isWXBrowser() {
				return (
					String(navigator.userAgent.toLowerCase().match(/MicroMessenger/i)) ===
					"micromessenger"
				);
			},
			//截取地址栏code
			getUrlCode(name) {
				return (
					decodeURIComponent(
						(new RegExp("[?|&]" + name + "=" + "([^&;]+?)(&|#|;|$)").exec(
							location.href
						) || [, ""])[1].replace(/\+/g, "%20")
					) || null
				);
			},
			//微信授权
			getWeChatCode() {
				if (!this.isOk) {
					uni.showToast({
						title: '请阅读并同意《用户服务协议》以及《登录政策》',
						icon: 'none'
					})
					this.isToast = true
					setTimeout(() => {
						this.isToast = false
					}, 500)
					return
				}
			 var ua = window.navigator.userAgent.toLowerCase();
			   if (ua.match(/MicroMessenger/i) == 'micromessenger') {
				   // console.log('这个是微信浏览器')
					const appId = 'wx160b3db67708860a'; // 替换为你的公众号AppID
					const redirectUri = encodeURIComponent(window.location.href); // 当前页面的URL，需要进行URL编码
					window.location.href =
						`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirectUri}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`;
			   } else {
			       const appId = 'wxe17646442a50807d'; // 替换为你的网站应用AppID
			       const redirectUri = encodeURIComponent(window.location.href); // 当前页面的URL，需要进行URL编码
			       // const redirectUri = encodeURIComponent('https://qiudaoyu.xikawa.net/#/pages/login/login'); // 当前页面的URL，需要进行URL编码
			       window.location.href =`
					https://open.weixin.qq.com/connect/qrconnect?appid=${appId}&redirect_uri=${redirectUri}&response_type=code&scope=snsapi_login&state=STATE#wechat_redirect
				   `;
			   }
				
			},
			navto(url) {
				uni.navigateTo({
					url: url
				})
			},
			backHome() {
				uni.switchTab({
					url: '/pages/index/index'
				})
			},
			navToXieyi(type) {
				if (type == 1) {
					// console.log('用户服务协议')
					uni.navigateTo({
						url: '/pages/xieyi/xieyi?title=用户服务协议&id=17'
					})
				} else {
					uni.navigateTo({
						url: '/pages/xieyi/xieyi?title=登录政策&id=15'
					})
				}
			},
			submitPhone() {
				var data = {
					email: this.noewPhone,
					sms_captcha: this.phonecode
				}
				if (data.email == '') {
					uni.showToast({
						title: '请输入手机号',
						icon: 'none'
					})
					return
				}
				if (data.sms_captcha == '') {
					uni.showToast({
						title: '请输入验证码',
						icon: 'none'
					})
					return
				}
				var emailRegex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;
				if (!emailRegex.test(data.email)) {
					uni.showToast({
						title: '请输入正确的手机号',
						icon: 'none'
					})
					return
				}
				this.$wqzApi.EmailCheck(data).then(res => {
					var parmse = {
						data: {
							...this.wx_info,
							user_email: this.noewPhone,
							type: this.loginType, //1微信
						}
					}
					this.$wqzApi.AppLoginBindingEmail(parmse).then(req => {
						uni.showToast({
							title: '登录成功',
							icon: 'success'
						})
						uni.setStorageSync('token', req.data)
						setTimeout(() => {
							uni.switchTab({
								url: '/pages/self/self'
							})
						}, 1500)
					}).catch(err => {
						uni.showToast({
							title: "绑定失败",
							icon: 'none'
						})
					})
				}).catch(err => {
					uni.showToast({
						title: '验证失败',
						icon: 'none'
					})
				})
			},


			login() {
				  if (!this.isOk) {
				  	uni.showToast({
				  		title: '请阅读并同意《用户服务协议》以及《登录政策》',
				  		icon: 'none'
				  	})
				  	this.isToast = true
				  	setTimeout(() => {
				  		this.isToast = false
				  	}, 500)
				  	return
				  }else {

					var data = {	
						"mobile": this.model, //手机号
						"password": this.code, //密码
					}
					if (this.isPhone) {
						if (this.code == '') {
							uni.showToast({
								title: '请输入密码',
								icon: 'none'
							})
							return
						}
						this.$gugoApi.pwdLogin(data).then(res => {
							uni.showToast({
								title: '登录成功',
								icon: 'success'
							})
							uni.setStorageSync('token', res.data.token)
							setTimeout(() => {
								uni.switchTab({
									url:'/pages/self/self'
								})
							}, 1500)
						}).catch(err => {
							uni.showToast({
								title: err.data.message,
								icon: 'none'
							})
							// console.log('错误信息', err)
						})
					} else {
						// 手机号验证码登录
						if (this.sms_captcha == '') {
							uni.showToast({
								title: '请输入验证码',
								icon: 'none'
							})
							return
						}
						var data = {
							"mobile": this.model,
							"sms_code": this.sms_captcha,
						}
						this.$gugoApi.mobileLogin(data).then(res => {
							uni.showToast({
								title: '登录成功',
								icon: 'success'
							})
							uni.setStorageSync('token', res.data.token)
							setTimeout(() => {
								uni.navigateBack()
							}, 1500)
						}).catch(err => {
							// console.log('错误信息', err)
						})
					}

				}
			},
			getCode(type) {
				// 获取手机号验证码
				var data = {
					mobile:this.model,
					email:this.model,
					type:type
				}
				if(this.model == ''){
					uni.showToast({
						title:'请输入手机号/邮箱',
						icon:'none'
					})
					return
				}
				var phone = /^[1][123456789][0-9]{9}$/;
				var isEmail = false
				if (this.model.includes("@")) {
					isEmail = true
					const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
					if(!emailRegex.test(this.model)){
						uni.showToast({
							title:'请输入正确的邮箱',
							icon:'none'
						})
						return
					}
				}else{
					if(!phone.test(this.model)){
						uni.showToast({
							title:'请输入正确的手机号',
							icon:'none'
						})
						return
					}
				}
				if(isEmail){
					delete data.mobile
				}else{
					delete data.email
				}
				// this.time = setInterval(()=>{
				// 	this.times -= 1
				// 	if(this.times == 0){
				// 		this.disabled = false
				// 		this.btn_text = `获取验证码`
				// 		clearInterval(this.time)
				// 		this.time = null
				// 		this.times = 120
				// 	}else{
				// 		this.disabled = true
				// 		this.btn_text = `${this.times}s后再次获取`
				// 	}
				// },1000)
				if(isEmail){
					// 获取邮箱验证码
					this.getEmailCode(data)
				}else{
					// 获取手机号验证码
					this.getPhoneCode(data)
				}
				
			},
			getPhoneCode(data) {
				this.$gugoApi.sendSmsCode(data).then(res => {
					this.time = setInterval(() => {
						this.times -= 1
						if (this.times == 0) {
							this.disabled = false
							this.btn_text = `获取验证码`
							clearInterval(this.time)
							this.time = null
							this.times = 120
						} else {
							this.disabled = true
							this.btn_text = `${this.times}s后再次获取`
						}
					}, 1000)
				}).catch(err => {
					uni.showToast({
						title: err.data.message,
						icon: 'none'
					})
				})
			},
			getEmailCode(data) {
				this.$gugoApi.post_email(data).then(res => {
					this.time = setInterval(() => {
						this.times -= 1
						if (this.times == 0) {
							this.disabled = false
							this.btn_text = `获取验证码`
							clearInterval(this.time)
							this.time = null
							this.times = 120
						} else {
							this.disabled = true
							this.btn_text = `${this.times}s后再次获取`
						}
					}, 1000)
				}).catch(err => {
					uni.showToast({
						title: err.data.message,
						icon: 'none'
					})
				})
			}
		}
	}
</script>

<style scoped>
	@import url('./login.css');

	
	/* @import url('../userInfo/userInfo.css'); */
</style>